//
//  CiotProduct.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/5/10.
//

import Combine

class CiotProductManager {
    static let shared = CiotProductManager()
    
    func requireProductCategory() -> AnyPublisher<DeviceAPI.ApplianceTypeList.Response, Error>
    {
        Future { promise in
            let api = DeviceAPI.ApplianceTypeList(body: nil)
            NetworkManager.shared.send(api, completion: { result in
                switch result {
                case .success(let response):
                    if let response = response.data
                    {
                        promise(.success(response))
                    }
                    else{
                        promise(.failure(NSError(domain: "获取产品分类失败", code: response.code as! Int, userInfo: [NSLocalizedDescriptionKey: response.msg ?? "无错误描述"])))
                    }
                case .failure(let error):
                    promise(.failure(error))
                }
            })
        }
        .eraseToAnyPublisher()
    }
    
    func requireProductsWithCategoryId(_ id: String) -> AnyPublisher<DeviceAPI.ProductListById.Response, Error>
    {
        Future { promise in
            let api = DeviceAPI.ProductListById(body: nil, pathValues: ["id": id])

            NetworkManager.shared.send(api, completion: { result in
                switch result {
                case .success(let response):
                    if let response = response.data
                    {
                        promise(.success(response))
                    }
                    else{
                        promise(.failure(NSError(domain: "获取产品列表失败", code: response.code as! Int, userInfo: [NSLocalizedDescriptionKey: response.msg ?? "无错误描述"])))
                    }
                case .failure(let error):
                    promise(.failure(error))
                }
            })
        }
        .eraseToAnyPublisher()
    }
    
    // 获取绑定列表
    func getBindedList() -> AnyPublisher<DeviceAPI.BindedDeviceList.Response, Error>
    {
        Future { promise in
            let api = DeviceAPI.BindedDeviceList(body: nil)
            NetworkManager.shared.send(api, completion: { result in
                switch result {
                case .success(let response):
                    if let deviceList = response.data
                    {
                        promise(.success(deviceList))
                    }
                    else{
                        promise(.failure(NSError(domain: "获取绑定列表失败", code: response.code as! Int, userInfo: [NSLocalizedDescriptionKey: response.msg ?? "无错误描述"])))
                    }
                case .failure(let error):
                    promise(.failure(error))
                }
            })
        }
        .eraseToAnyPublisher()
    }
}
